package com.dongwu.manager.api;

import java.util.*;

import com.dongwu.common.utils.Exceptions;
import com.dongwu.common.utils.ListUtils;
import com.dongwu.manager.dto.*;
import com.dongwu.manager.entity.*;
import com.dongwu.manager.service.*;
import com.google.common.collect.Maps;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import com.dongwu.common.constants.DongwuManagerConstant;
import com.dongwu.common.dto.Result;
import com.dongwu.config.Slink;
import com.gexin.fastjson.JSON;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api")
public class ApiController {

	@Autowired
	private DeviceService deviceService;
	@Autowired
	private ProductService productService;
	@Autowired
	private AppVersionService appVersionService;
	@Autowired
	private TemplateTypeService templateTypeService;

//	@Autowired
//	private IUserService iUserService;

	@Autowired
	private FeedBackService feedBackService;

	@Autowired
	private ReviewCountService reviewCountService;
	@Autowired
	private MarketService marketService;
	
	@Autowired
	private CultureService cultureService;
	@Autowired
	private MediaService mediaService;
	@Autowired
	private OpenMarketService openMarketService;
	@Autowired
	private AppTemplateService appTemplateService;
	@Autowired
	private DeviceProductRecordService deviceProductRecordService;
	@Autowired
	private DeviceAdsRecordService deviceAdsRecordService;
	@Autowired
	private AdsClassifyService adsClassifyService;
	@Autowired
	private AdvertisingService advertisingService;

	/**
	 * 获取设备配置信息
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/device/{sn}", method = RequestMethod.GET)
	@ApiOperation(value = DongwuManagerConstant.DEVICEDETAIL)
	public Result get(
			@ApiParam(value = DongwuManagerConstant.DEVICESN, required = true) @RequestParam(required = true) @PathVariable String sn) {

		Device device = deviceService.findBySn(sn);
		if (device == null) {
			return Result.errorResult("请在广投墙售前APP注册!");
		}
		DeviceData data = new DeviceData();
		BeanUtils.copyProperties(device, data);
		data.setId(device.getId());
		// 返回设备状态
		data.setStatus(device.getStatus().toString());
		// 根据屏幕类型获取对应的一个版本
		AppVersion apv = appVersionService.findByDeviceType(device.getShowType());
		if (apv == null) {
			return Result.errorResult("找不到设备对应的APP版本！");
		}
		data.setDownUrl(apv.getDownUrl());
		//清除多余的user数据
		//data.getAppTemplate().setUser(null);
		return Result.successResult(data);
	}
	/**
	 * 获取广告分类信息
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getAdsForClassify", method = RequestMethod.GET)
	@ApiOperation(value = DongwuManagerConstant.GET_ADS_CALSSIFY_LIST)
	public Result geAdsClassify(
			@ApiParam(value = DongwuManagerConstant.ADSCLASSIFYID, required = true) @RequestParam(required = true) @PathVariable String classifyId,
			@ApiParam(value = DongwuManagerConstant.DEVICEID, required = true) @RequestParam(required = true) @PathVariable String deviceId) {
		AdsClassify adsc = adsClassifyService.get(classifyId);
		if(adsc == null){
			return Result.errorResult("分类不存在！");
		}
		//如果是广告类型的分类
		if(adsc.getType().equals("0")){
			List<Advertising> ads = advertisingService.getAdsForClassify(deviceId, 0, classifyId);
			List<AdvertisingData> adsl= new ArrayList<AdvertisingData>();
			for (Advertising advertising : ads) {
				AdvertisingData adsd= new AdvertisingData();
				BeanUtils.copyProperties(advertising, adsd);
				adsl.add(adsd);
			}
			return Result.successResult(adsl);
		}
		//如果是新零售类型的分类
		if(adsc.getType().equals("1")){
			List<Product> p = productService.getProductForDevId(deviceId, classifyId);
			List<ProductData> pdl = new ArrayList<ProductData>();
			for (Product product : p) {
				ProductData pd = new ProductData();
				BeanUtils.copyProperties(product, pd);
				pd.setId(product.getId());
				pdl.add(pd);
			}
			return Result.successResult(pdl);
		}
		return Result.successResult();
	}
	/**
	 * 获取设备的商品列表
	 * 
	 * @param deviceId
	 * @return
	 */
	@RequestMapping(value = "/device/products/{deviceId}", method = RequestMethod.GET)
	@ApiOperation(value = DongwuManagerConstant.DEVICEPRODUCTS)
	public Result getProducts(
			@ApiParam(value = DongwuManagerConstant.DEVICEID, required = true) @RequestParam(required = true) @PathVariable String deviceId) {

		List<DeviceProductRecord> dprs = deviceProductRecordService.findByDeviceId(deviceId);
		if(dprs == null){
			return Result.successResult();
		}
		Function<DeviceProductRecord, ProductData> function = new Function<DeviceProductRecord, ProductData>() {
			@Override
			public ProductData apply(DeviceProductRecord input) {
				ProductData data = new ProductData();
				data.setId(input.getProductid());
				data.setName(input.getProduct().getName());
				data.setImage(input.getProduct().getImage());
				return data;
			}
		};
		return Result.successResult(Lists.transform(dprs, function));
	}
	/**
	 * 获取设备广告列表
	 * 
	 * @param deviceId,templateId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/device/advertising", method = RequestMethod.POST)
	@ApiOperation(value = DongwuManagerConstant.DEVICEPRODUCTS)
	public Result getAdvertising(
			@ApiParam(value = DongwuManagerConstant.DEVICEID, required = true) @RequestParam(required = true) String deviceId) {
		Device dev= deviceService.get(deviceId);
		if(dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("005") || dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("008")){
			List<DeviceProductRecord> dprList = deviceProductRecordService.findByDeviceId(deviceId);
			List<ProductData> productDataList1 = Lists.newLinkedList();
			Function<DeviceProductRecord, ProductData> function = new Function<DeviceProductRecord, ProductData>() {
				@Override
				public ProductData apply(DeviceProductRecord input) {
					ProductData data = new ProductData();
					data.setId(input.getProductid());
					data.setName(input.getProduct().getName());
					data.setImage(input.getProduct().getImage());
					Product p = input.getProduct();
					int ishot = p.getIshot();
					data.setIshot(ishot);
					if(input.getProduct().getAdsClassify() != null){
						data.setAdsClassifyId(input.getProduct().getAdsClassify().getId());
					}
					return data;
				}
			};
			List<ProductData> productDataList = Lists.transform(dprList, function);
			for(ProductData p : productDataList){
				if(p.getIshot() == 1){
					productDataList1.add(p);
				}
			}
			//如果当前设备是格子铺
			if(dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("005")){
				if(dprList == null){
					return Result.successResult();
				}
				HashMapData hashMapData = new HashMapData();
				hashMapData.setProductDataList(productDataList);
				hashMapData.setAdsClassifyDatas(Lists.newArrayList());
				hashMapData.setIshot(productDataList1);
				hashMapData.setAdvertisingDatas(Lists.newArrayList());
				return Result.successResult(hashMapData);
			}else{
				List<DeviceAdsRecord> darList = Lists.newArrayList();
				List<AdvertisingData> adsList = Lists.newArrayList();
				if("008".equals(dev.getAppTemplate().getTemplateType().getTemplateTypeSn())){
					darList = deviceAdsRecordService.findByDeviceId(deviceId, 0);
				}
				if(darList.size() > 0){
					Function<DeviceAdsRecord, AdvertisingData> function1 = new Function<DeviceAdsRecord, AdvertisingData>() {
						@Override
						public AdvertisingData apply(DeviceAdsRecord input) {
							AdvertisingData data = new AdvertisingData();
							BeanUtils.copyProperties(input.getAdvertising(), data);
							if(input.getAdvertising().getTeltemplatelayout()!=null){
								data.setCode(input.getAdvertising().getTeltemplatelayout().getCode());
							}
							if(input.getAdvertising().getAdsclassify()!=null){
								data.setAdsclassifyId(input.getAdvertising().getAdsclassify().getId());
							}
							return data;
						}
					};
					adsList= Lists.transform(darList, function1);
				}
				List<AdsClassifyData> mapList =  Lists.newLinkedList();
				List<AdsClassify> adsClassifyList = adsClassifyService.queryByType("1");
				for(AdsClassify adsClassify:adsClassifyList){
					AdsClassifyData adsClassifyData = new AdsClassifyData();
					BeanUtils.copyProperties(adsClassify, adsClassifyData);
					adsClassifyData.setId(adsClassify.getId());
					List<ProductData> newProductDataList = Lists.newLinkedList();
					for(ProductData productData : productDataList){
						if(adsClassify.getId().equals(productData.getAdsClassifyId())){
							newProductDataList.add(productData);
						}
						adsClassifyData.setProductDataList(newProductDataList);
					}
					mapList.add(adsClassifyData);
				}
				HashMapData hashMapData = new HashMapData();
				hashMapData.setProductDataList(Lists.newLinkedList());
				hashMapData.setAdsClassifyDatas(mapList);
				hashMapData.setIshot(productDataList1);
				hashMapData.setAdvertisingDatas(adsList);
				return Result.successResult(hashMapData);
			}
		}else{
			List<DeviceAdsRecord> darList = deviceAdsRecordService.findByDeviceId(deviceId, 0);
			if(darList == null){
				return Result.successResult();
			}
			Function<DeviceAdsRecord, AdvertisingData> function1 = new Function<DeviceAdsRecord, AdvertisingData>() {
				@Override
				public AdvertisingData apply(DeviceAdsRecord input) {
					AdvertisingData data = new AdvertisingData();
					BeanUtils.copyProperties(input.getAdvertising(), data);
					//如果布局不为空则赋值给AdvertisingData.code
					if(input.getAdvertising().getTeltemplatelayout()!=null){
						data.setCode(input.getAdvertising().getTeltemplatelayout().getCode());
					}
					//如果分类不为空则赋值给AdvertisingData.code
					if(input.getAdvertising().getAdsclassify()!=null){
						data.setAdsclassifyId(input.getAdvertising().getAdsclassify().getId());
					}
					return data;
				}
			};
			List<AdvertisingData> adsList= Lists.transform(darList, function1);
			
//			如果是优惠券+图片的混合模板
			if(dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("009")){
				Map<String,Object> map = new HashMap<String,Object>();
				for (AdvertisingData advertisingData : adsList) {
					//判断这个code是否已存在map中
					if(map.containsKey(advertisingData.getAdsType().toString())){
						List<AdvertisingData> adl= (List<AdvertisingData>) map.get(advertisingData.getAdsType().toString());
						adl.add(advertisingData);
					}else{
						List<AdvertisingData> adList=new ArrayList<AdvertisingData>();
						adList.add(advertisingData);
						map.put(advertisingData.getAdsType().toString(),adList );
					}
				}
				if(map.containsKey("0")){
					map.put("imageList", map.get("0"));
					map.remove("0");
				}
				if(map.containsKey("4")){
					map.put("couponList", map.get("4"));
					map.remove("4");
				}
				return Result.successResult(map);
			}
			
//			如果是优惠券则返回双层list
			if(dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("004")){
				List<List<AdvertisingData>> adsLists = ListUtils.averageList(adsList, 6);
				return Result.successResult(adsLists);
			}

//			如果是竖屏旅游模板
			if(dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("007")||dev.getAppTemplate().getTemplateType().getTemplateTypeSn().equals("006")){
				Map<String,Object> map = new HashMap<String,Object>();
				for (AdvertisingData advertisingData : adsList) {
					//过滤掉关联的多余用户数据
					if(advertisingData.getProduct() != null && advertisingData.getProduct().getUser() != null){
						advertisingData.getProduct().setUser(null);
					}
					//过滤掉关联的多余用户数据
					if(advertisingData.getProduct() != null){
						//过滤掉关联的多余分类数据
						advertisingData.getProduct().setAdsClassify(null);
					}
					
					//判断这个code是否已存在map中
					if(map.containsKey(advertisingData.getCode())){
						List<AdvertisingData> adl= (List<AdvertisingData>) map.get(advertisingData.getCode());
						adl.add(advertisingData);
					}else{
						List<AdvertisingData> adList=new ArrayList<AdvertisingData>();
						adList.add(advertisingData);
						map.put(advertisingData.getCode(),adList );
					}
				}

				return Result.successResult(map);
			}
			return Result.successResult(Lists.transform(darList, function1));
		}
	}

	/**
	 * 商品同步
	 *
	 * @param parmJson
	 * @return
	 */
	@RequestMapping(value = "/syncProduct", method = RequestMethod.POST)
	@ApiOperation(value = DongwuManagerConstant.PRODUCTSYNC)
	public Result syncProduct(@RequestParam(required = true) String parmJson) {

		List<ProductData> productDatas = JSON.parseArray(parmJson, ProductData.class);
		if (productDatas == null || productDatas.isEmpty()) {
			return Result.successResult();
		}

		productService.syncProduct(productDatas);
		return Result.successResult();

	}

	/**
	 * 获取商品详情
	 * 
	 * @param productId
	 * @return
	 */
	@ApiOperation(value = DongwuManagerConstant.PRODUCTDETAIL)
	@RequestMapping(value = "/product/{productId}", method = RequestMethod.GET)
	public Result getProduct(
			@ApiParam(value = DongwuManagerConstant.PRODUCTID, required = true) @RequestParam(required = true) @PathVariable String productId,
			@ApiParam(value = DongwuManagerConstant.DEVICEID, required = true) @RequestParam(required = true) String deviceid) {

		Product product = productService.get(productId);
		ProductData productData = new ProductData();
		BeanUtils.copyProperties(product, productData);
		// String s="颜色:白色,黑色|容量:68,128";

		if (!StringUtils.isEmpty(product.getSpecification())) {
			Map<String, String> join = Splitter.on("|").trimResults().omitEmptyStrings().withKeyValueSeparator(":")
					.split(product.getSpecification());

			Set<String> keyset = join.keySet();
			List<SpecificationData> sps = Lists.newArrayList();
			for (String key : keyset) {
				SpecificationData sp = new SpecificationData();
				sp.setSpecification_name(key);
				sp.setSpecification(Splitter.on(",").trimResults().omitEmptyStrings().splitToList(join.get(key)));
				sps.add(sp);
			}
			productData.setSpecificationList(sps);
		}
		Device device = deviceService.findById(deviceid);
		if (product.getType().equals(Product.Type.outimport)) {
			productData.setPathmobile(
					product.getPathUrl() + Base64.getEncoder().encodeToString(("goodsid=" + product.getGoodsid()
							+ "&device=" + device.getId() + "&yukeNum=" + device.getYunkeNum()).getBytes()));
			/*
			 * productData.setPathmobile(product.getPathUrl() +
			 * Base64.getEncoder().encodeToString(("goodsid="+product.getGoodsid
			 * ()+"&userId=1003937279087164267&time=2017-12-05 14:36:55"
			 * ).getBytes()));
			 */
		} else {
			productData.setPathmobile(product.getPathUrl());
		}
		productData.setId(productId);
		productData.setVideo(product.getVideo());
		// 如果短链为空则调用短链系统创建
		if (product.getSlink() == null) {
			productData.setSlink(Slink.getSlink(productData.getPathmobile()));
			// // 调用短链系统
			// try {
			// String httpResponse =
			// HttpClientUtils.HttpGetResStr(DongwuManagerConstant.SLINKSERVERURL
			// + "?userId="
			// + DongwuManagerConstant.SLINKSERVERUSERID + "&originalUrl=" +
			// productData.getPathmobile());
			// Map<String, Object> mapTypes = JSON.parseObject(httpResponse);
			// if (Integer.parseInt(mapTypes.get("code").toString()) == 0) {
			// product.setSlink(mapTypes.get("response").toString());
			// }
			// } catch (Exception e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
		}
		ReviewCount count = reviewCountService.findByDeviceid(deviceid);
		if (count == null) {
			count = new ReviewCount();
			count.setCount(1);
			count.setProductid(productId);
			count.setDeviceid(deviceid);
			count.setUser(product.getUser());
		} else {
			count.setCount(count.getCount() + 1);
		}
		reviewCountService.update(count);

		return Result.successResult(productData);
	}

	/**
	 * 获取设备app版本信息
	 *
	 * @return
	 */
	@ApiOperation(value = DongwuManagerConstant.APPVERSION)
	@RequestMapping(value = "/appversion", method = RequestMethod.GET)
	public Result appVersion(
			@ApiParam(value = DongwuManagerConstant.DEVICEIDTYPE, required = true) @RequestParam(required = true) Integer deviceType) {
		AppVersion version = appVersionService.findByDeviceType(deviceType);
		return Result.successResult(version);
	}

	/**
	 * 意见反馈
	 *
	 * @return
	 */
	@ApiOperation(value = DongwuManagerConstant.FEEDBACK)
	@RequestMapping(value = "/feedBack", method = RequestMethod.POST)
	public Result feedBack(@RequestBody FeedBackData feedBackData) {
		Device device = new Device();
		FeedBack feedBack = new FeedBack();

		BeanUtils.copyProperties(feedBackData, feedBack);

		feedBack.setDevice(device);

		feedBack.setState(FeedBack.stateType.unread);

		device.setId(feedBackData.getDevId());
		try {
			FeedBack ResfeedBack = feedBackService.save(feedBack);
			return Result.successResult(ResfeedBack);
		} catch (Exception e) {
			// TODO: handle exception
			return Result.errorResult("请求异常");
		}

	}

	@ApiOperation(value = DongwuManagerConstant.MARKET)
	@RequestMapping(value = "/market/{deviceId}", method = RequestMethod.POST)
	public Result market(@PathVariable("deviceId") String deviceId) {
		List<MarketData> marketDataList = new ArrayList<MarketData>();
		try {
			List<OpenMarket> omL = openMarketService.findByDeviceId(deviceId);
			if(omL == null){
				return Result.successResult();
			}
			for (int i = 0; i < omL.size(); i++) {
				Market market = marketService.get(omL.get(i).getMarketId());
				MarketData md = new MarketData();
				md.setId(market.getId());
				md.setName(market.getName());
				md.setMarketClassify(market.getMarketClassify());
				md.setType(market.getType());
				md.setUrl(market.getUrl());
				marketDataList.add(md);
			}
			return Result.successResult(marketDataList);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.errorResult("请求异常");
		}

	}

	/**
	 * 注册设备
	 *
	 * @param deviceData
	 * @return
	 */
	@ApiOperation(value = DongwuManagerConstant.REGISTERDEVICE)
	@RequestMapping(value = "/registerDevice", method = RequestMethod.POST)
	public Result registerDevice(@RequestBody DeviceData deviceData) {
		Device device = deviceService.findBySn(deviceData.getSn());
		AppTemplate appTemplate = new AppTemplate();
		if(null != deviceData.getAppTemplateId() && ""!=deviceData.getAppTemplateId()){
			appTemplate = appTemplateService.get(deviceData.getAppTemplateId());
		}else{
			TemplateType templateType = templateTypeService.findByTemplateTypeSn("005");
			if(templateType != null){
				appTemplate = appTemplateService.findByTemplateTypeList(templateType.getId());
			}
		}
		if (device != null && device.getStatus() == Device.Status.passApproval) {
			return Result.errorResult("你的设备已审核通过！");
		}
		if(device == null){
			device = new Device();
		}
		BeanUtils.copyProperties(deviceData, device, "id","appTemplate");
		device.setStatus(Device.Status.pendingApproval);
		device.setRemark(null);
		device.setAppTemplate(appTemplate);
		device.setIMStatus(Device.iMStatusType.Offline);
		device.setSwitchingSpeed(2);
		if("005".equals(appTemplate.getTemplateType().getTemplateTypeSn()) ){
			device.setTemplateTypeSn("002");
		}else if("006".equals(appTemplate.getTemplateType().getTemplateTypeSn()) ||"007".equals(appTemplate.getTemplateType().getTemplateTypeSn())
				|| "008".equals(appTemplate.getTemplateType().getTemplateTypeSn())){
			device.setTemplateTypeSn("003");
		}else{
			device.setTemplateTypeSn("001");
		}
		device.setTemplateTypeSn(appTemplate.getTemplateType().getTemplateTypeSn());
		deviceService.save(device);
		BeanUtils.copyProperties(device,deviceData);
		if(appTemplate != null){
			deviceData.setAppTemplateName(device.getAppTemplate().getName());
		}
		deviceData.setAppTemplate(null);
		return Result.successResult(deviceData);
	}
	/**
	 * 获取广投墙文旅列表
	 * 
	 * @param sn
	 * @param
	 * @return
	 */
	@ApiOperation(value = DongwuManagerConstant.CULTURELIST)
	@RequestMapping(value = "/getCultureList", method = RequestMethod.POST)
	public Result getCultureList(@ApiParam(name="sn",value = DongwuManagerConstant.DEVADDRESS, required = true) @RequestParam(required = true) String sn) {
		List<List<CultureData>> cdResList = new ArrayList<List<CultureData>>();
		/*获取设备信息*/
		Device device = deviceService.findBySn(sn);
		/*获取大图*/
		List<Culture> resMaxImg = cultureService.findCulture(device.getId(), 0);
		/*获取中图*/
		List<Culture> resMedImg = cultureService.findCulture(device.getId(), 2);
		
		if(resMaxImg == null && resMedImg == null){
			return Result.successResult();
		}
		for(int i=0; i < i+1;i++){
			List<CultureData> cdList = new ArrayList<CultureData>();
			List<Culture> cList = new ArrayList<Culture>();
			if(resMaxImg.size() > 0 && i < resMaxImg.size()){
				cList.add(resMaxImg.get(i));
			}
			if(resMedImg.size() > 0 && i*2+1 <= resMedImg.size()){
				cList.add(resMedImg.get(i*2));
				
				if(resMedImg.size() > i*2+1){
					cList.add(resMedImg.get(i*2+1));
				}
			}
			if(cList.size() == 0){
				break;
			}
			for(int y=0;y<cList.size();y++){
				CultureData cd = new CultureData();
				BeanUtils.copyProperties(cList.get(y), cd, "id","device","userid");
				cd.setTitleType(String.valueOf(cList.get(y).getTitleType()));
				cdList.add(cd);
			}
			cdResList.add(cdList);
		}
		return Result.successResult(cdResList);

	}
	/**
	 * 获取广投墙传媒列表
	 * 
	 * @param sn
	 * @param pageNo
	 * @return
	 */
	@ApiOperation(value = DongwuManagerConstant.MEDIALIST)
	@RequestMapping(value = "/getMediaList", method = RequestMethod.POST)
	public Result getMediaList(@ApiParam(name="sn",value = DongwuManagerConstant.DEVADDRESS, required = true) @RequestParam(required = true) String sn,
			@ApiParam(name="pageNo",value = DongwuManagerConstant.PAGENO, required = true) @RequestParam(required = true) Integer pageNo) {
		List<MediaData> mdList = new ArrayList<MediaData>();
		List<Media> mList = new ArrayList<Media>();
		/*获取设备信息*/
		Device device = deviceService.findBySn(sn);
		/*获取大图*/
		List<Media> resMaxImg = mediaService.findMedia(device.getId(), 0, pageNo*2, 2);
		/*获取小图*/
		List<Media> resMinImg = mediaService.findMedia(device.getId(), 1, pageNo*8, 8);
		/*获取中图*/
		List<Media> resMedImg = mediaService.findMedia(device.getId(), 2, pageNo*8, 8);
		
		if(resMaxImg == null && resMedImg == null && resMinImg == null){
			return Result.successResult();
		}
		for(int i=0; i<i+1; i++){
			if(resMaxImg.size() > 0 && i < resMaxImg.size()){
				mList.add(resMaxImg.get(i));
			}
			if(resMedImg.size() > 0 && i < resMedImg.size()){
				mList.add(resMedImg.get(i));
			}
			if(resMinImg.size() > 0 && i < resMinImg.size()){
				mList.add(resMinImg.get(i));
			}
			if(mList.size() == resMaxImg.size()+resMedImg.size()+resMinImg.size()){
				break;
			}
		}
		for(int y=0;y<mList.size();y++){
			MediaData md = new MediaData();
			BeanUtils.copyProperties(mList.get(y), md, "id","device","userid");
			md.setTitleType(String.valueOf(mList.get(y).getTitleType()));
			mdList.add(md);
		}
		return Result.successResult(mdList);

	}

	@ApiOperation(value = DongwuManagerConstant.APPTEMPLATE)
	@RequestMapping(value = "/getAppTemplate", method = RequestMethod.GET)
	public Result queryTree(@RequestParam(required = true) Integer showType) {
		try {
			List<Map<String, Object>> nodes = Lists.newArrayList();
            TemplateType templateType = templateTypeService.findByTemplateTypeSn("005");
            AppTemplate appTemplate = appTemplateService.findByShowTypeAndIsDefault(showType,true);
            if(appTemplate == null){
                AppTemplate appt = new AppTemplate();
                appt.setShowType(showType);
                if(appt.getShowType() == 0){
                    appt.setResolution("800*600");
                    appt.setName("默认模板（横屏）");
                }else{
                    appt.setResolution("600*800");
                    appt.setName("默认模板（竖屏）");
                }
                appt.setTemplateType(templateType);
                appt.setDefault(true);
                appt.setStatus(1);
                appTemplateService.save(appt);
            }
			Iterable<AppTemplate> appTemplates = appTemplateService.findByStatusAndShowType(showType);
			for (Iterator<AppTemplate> iter = appTemplates.iterator(); iter.hasNext();) {
				getAppTemplate(iter.next(), nodes);
			}
			return Result.successResult(nodes);
		} catch (Exception e) {
			String msg = Exceptions.getMessage(e);
			return Result.errorResult(msg);
		}

	}

	private void getAppTemplate(AppTemplate appTemplate, List<Map<String, Object>> nodes) {
		Map<String, Object> appTemplateData = Maps.newHashMap();
		appTemplateData.put("tId", appTemplate.getId());
		appTemplateData.put("id", appTemplate.getId());
		appTemplateData.put("name", appTemplate.getName());
		nodes.add(appTemplateData);
	}


//	/**
//	 * 微信红包接口
//	 * 
//	 * @param weiXinRedPack
//	 * @return
//	 */
//	@ApiOperation(value = DongwuManagerConstant.WEIXINREDPACK)
//	@RequestMapping(value = "/weiXinRedPack/{openid}", method = RequestMethod.POST)
//	public Result WeiXinRedPackge(@PathVariable("openid")String openid) {
//		
//		WeiXinRedPack wxrp = new WeiXinRedPack();
////		非必填参数
////		wxrp.setConsume_mch_id("test");
////		wxrp.setRisk_info("test");
////		wxrp.setScene_id("test");
//		wxrp.setMch_billno(UUID.randomUUID().toString().replaceAll("-", "").substring(0,27));
//		wxrp.setAct_name("新鲜的大红包");
//		wxrp.setClient_ip("172.24.171.81");
//		wxrp.setNonce_str(UUID.randomUUID().toString().replaceAll("-", ""));
//		wxrp.setRe_openid(openid);
//		wxrp.setRemark("这是一个测试备注");
//		wxrp.setWishing("这是一个测试祝福语");
//		wxrp.setTotal_amount(100);
//		wxrp.setTotal_num(1);
//		wxrp.setSend_name("东吴科技");
//		wxrp.setWxappid("wx5d42f25aa276aeb3");
//		wxrp.setMch_id("1328753901");
//		
//		
//		//使用参数生成签名
//		String sign = RedPackConfig.createSendRedPackOrderSign(wxrp);
//		wxrp.setSign(sign);
//		//序列化Xml
//		String xml = JaxbMapper.toXml(wxrp);
//		//请求
//		String response = RedPackConfig.SSL(TencentIMConstants.WEIXINREDPACKURL, xml);
//		//反序列化Xml
//		Map<String, String> web = JaxbMapper.parseXml(response);
//		System.err.println(web.toString());
//		return Result.successResult(web);
//
//	}
}
